## Controller Python Script "create_doc_feedback_product"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Create a document with feedback content
##

REQUEST=context.REQUEST
dir_products = 'prodotti'
dir_feedback = 'feedback'
#types_to_filter = 'Folder'

from Products.CMFCore.utils import getToolByName

#portal_catalog = getToolByName(context, 'portal_catalog')
workflowTool = getToolByName(context, 'portal_workflow')
container = getattr(context, dir_feedback, None)

subject = REQUEST.get('subject', '')
product = REQUEST.get('product', '')
rating = REQUEST.get('rating', '')
message = REQUEST.get('message', '')

#ricavo l'UID del prodotto da collegare
dir_prodotti = getattr(context, dir_products, None)
obj_prod = dir_prodotti[product]
pid = obj_prod.UID() 
p_title = obj_prod.title

# create with a random id
newId = context.generateUniqueId('Document')

if not product in container.objectIds():
   container.invokeFactory(type_name="Folder", id=product)
   obj_fold = container[product]
   obj_fold.setTitle(p_title)
   workflowTool.doActionFor(obj_fold, "publish")
   obj_fold.reindexObject()
else:
   obj_fold = container[product]
   
obj_fold.invokeFactory(type_name="Document", id=newId)

obj = obj_fold[newId]

obj.setTitle(subject)
obj.setDescription('Voto: '+rating)
obj.setText(message)
obj.setRelatedItems([pid])
workflowTool.doActionFor(obj, "submit")

obj.reindexObject()

REQUEST.set('feed_id', newId)

return state